from flask import Flask, request, render_template, redirect, flash
import re

from flask_sqlalchemy import SQLAlchemy

app = Flask (__name__)

app.config.from_pyfile ("config.py")

db = SQLAlchemy (app)


# ========================================================数据表字段=====================================================

class Goods (db.Model):
    __tablename__ = "goods"

    id = db.Column (db.Integer, primary_key = True, autoincrement = True)

    name = db.Column (db.String (150), unique = True)

    price = db.Column (db.String)

    img = db.Column (db.String (150), nullable = True)


# ========================================================添加数据表页面==================================================

@app.route ("/init")
def get_init ():
    db.create_all ()
    return "数据表创建成功"


# ========================================================商品添加页面===================================================
@app.route ("/add", methods = ["GET", "POST"])
def add ():
    if request.method == "GET":
        return render_template ("add.html")
    else:
        name = request.form.get ("name")
        price = request.form.get ("price")
        price1 = re.match ("^\d+\d$", price)
        if price1:
            good = Goods (name = name, price = price)
            db.session.add (good)
            db.session.commit ()
            return "添加成功"
        else:
            flash ("价格添加非整形")
            return render_template ("add.html")


# ========================================================商品展示页面===================================================

@app.route ("/list")
def list ():
    goods_list = Goods.query.all ()
    return render_template ("goods_list.html", goods_list = goods_list)


# ========================================================g过滤器========================================================

@app.template_filter ("yuan")
def yuan (value):
    return str ((int (value)) / 100) + "元"


# ========================================================过滤器========================================================

@app.route ("/orders")
def orders ():
    goods_list = Goods.query.order_by ((Goods.price).desc ()).all ()
    return render_template ("goods_list.html", goods_list = goodxs_list)


# ========================================================程序入口=======================================================

if __name__ == '__main__':
    app.run ()
